package com.ask.forMe.controller.business;

import com.ask.forMe.model.entity.Item;
import com.ask.forMe.model.entity.Result;
import com.ask.forMe.service.ItemService;
import com.ask.forMe.service.RecommendService;
import com.ask.forMe.task.RecommendTask;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Set;

import static com.ask.forMe.constant.RedisConstant.RECOMMEND_DAILY_KEY;

@RestController
@RequestMapping("/recommend")
@Slf4j
public class RecommendController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RecommendTask recommendTask;

    @Autowired
    private ItemService itemService;
    @Autowired
    private RecommendService recommendService;

    @GetMapping("/daily")
    public Result getRecommendationFromRedis(@RequestParam Long userId) {
        // key构建
        String dateStr = LocalDateTime.now().format(DateTimeFormatter.BASIC_ISO_DATE);
        String key = dateStr + ":" + RECOMMEND_DAILY_KEY + userId;
        // 查询redis
        Set<Long> itemIds = redisTemplate.opsForSet().members(key);
        log.info("time-{},recommend for user{}, list:{}", dateStr, userId, itemIds);
        // 查询数据库(by ids)
        List<Item> items = itemService.listByIds(itemIds);
        return Result.success(items);
    }


    /**
     * 用户点击<换一批>，生成新的一批推荐
     *
     * @param userId
     */
    @GetMapping("/refresh")
    public Result getNewRecommendationsForUser(@RequestParam Long userId, @RequestParam(defaultValue = "10") int topN) {
        List<Item> items = recommendService.refreshRecommendation(userId, topN);
        if (items == null || items.isEmpty())
                return Result.fail("推荐光了！");
        log.info("为用户{}生成新的一批推荐：{}", userId, items);
        return Result.success(items);
    }

    /**
     * 每日定时任务，生成所有用户的推荐列表
     * @return
     */
    @GetMapping("/task")
    @Operation(summary = "每日定时任务")
    public Result taskTest() {
        recommendTask.generateDailyRecommendations();
        return Result.success();
    }
}
